package com.boarsoft.boar.gateway.wechat.biz.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.PostConstruct;

import org.hibernate.query.Query;
import org.hibernate.type.StringType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.gateway.wechat.biz.TempletBiz;
import com.boarsoft.boar.gateway.wechat.common.WechatConfig;
import com.boarsoft.boar.gateway.wechat.common.WechatConstance;
import com.boarsoft.boar.gateway.weixin.biz.impl.WxBizImpl;
import com.boarsoft.boar.gateway.weixin.common.WxFormatData;
import com.boarsoft.cache.Cache;
import com.boarsoft.wechat.entity.MsgType;
import com.boarsoft.wechat.entity.WeChatDictionary;
import com.boarsoft.wechat.entity.WeChatTemplate;
import com.google.gson.Gson;

@Transactional
@Component("templetBiz")
public class TempletBizImpl extends WxBizImpl implements TempletBiz {

	@Autowired
	private Cache cache;

	private Logger log = LoggerFactory.getLogger(TempletBizImpl.class);

	@PostConstruct
	public void init() {
		try {
			loadTemplate();
			loadWeChatDictionary();
		} catch (Exception e) {
			log.error("微信模板数据初始化加载失败...", e);
		}
	}

	@Transactional(readOnly = true)
	public void loadTemplate() throws Exception {

		StringBuilder hql = new StringBuilder();
		hql.append(" FROM ").append(WeChatTemplate.class.getName());
		hql.append(" WHERE ");
		hql.append(" status = :status ");
		hql.append(" AND platformFakeId = :platformFakeId ");
		Query<WeChatTemplate> query = dao.createQuery(WeChatTemplate.class, hql.toString());
		query.setParameter("status", "1", new StringType());
		query.setParameter("platformFakeId", WechatConfig.getProperty("weixin.platformFakeId"), new StringType());

		List<WeChatTemplate> list1 = query.list();
		List<MsgType> list2 = new ArrayList<MsgType>();
		for (WeChatTemplate template : list1) {
			list2.addAll(template.getMsgTypes());
			template.setMsgTypes(null);
			cache.put(WechatConstance.TEMPLET_CACHE_NAME, template.getCode(), template);
			log.info("微信模板数据初始化|{}", new Gson().toJson(template));
		}

		for (MsgType type : list2) {
			if ("1".equals(type.getStatus())) {
				String msgCode = type.getMsgCode();
				if (type.getWechatTemplate() != null && msgCode != null) {
					String tempCode = type.getWechatTemplate().getCode();
					cache.put(WechatConstance.TEMPLET_TYPE_CACHE_NAME, tempCode + "_" + msgCode, tempCode);
					log.info("微信模板数据初始化|{}|{}", msgCode, tempCode);
				} else {
					log.error("微信模板数据数据异常|{}", msgCode);
				}
			}
		}
	}

	@Transactional(readOnly = true)
	public void loadWeChatDictionary() throws Exception {

		StringBuilder hql = new StringBuilder();
		hql.append(" FROM ").append(WeChatDictionary.class.getName());
		hql.append(" WHERE ");
		hql.append(" status = :status ");
		hql.append(" order by dataKey");
		Query<WeChatDictionary> query = dao.createQuery(WeChatDictionary.class, hql.toString());
		query.setParameter("status", "1", new StringType());

		WxFormatData.dictionaryMap = new HashMap<String, List<WeChatDictionary>>();
		String frontName = null;
		String name = null;
		List<WeChatDictionary> list = query.list();
		for (WeChatDictionary dictionary : list) {
			name = dictionary.getDictionaryName();
			if (!name.equals(frontName)) {
				WxFormatData.dictionaryMap.put(name, new ArrayList<WeChatDictionary>());
			}
			WxFormatData.dictionaryMap.get(name).add(dictionary);
			frontName = name;
			log.info("微信数据字典{}", new Gson().toJson(dictionary));
		}
	}

	@Override
	@Transactional(readOnly = true)
	public WeChatTemplate getTemplateById(String tempId) throws Exception {
		StringBuilder hql = new StringBuilder();
		hql.append(" FROM ").append(WeChatTemplate.class.getName());
		hql.append(" WHERE ");
		hql.append(" id = :tempId ");
		Query<WeChatTemplate> query = dao.createQuery(WeChatTemplate.class, hql.toString());
		query.setParameter("tempId", tempId, new StringType());
		List<WeChatTemplate> list = query.list();
		if (list != null && list.size() != 0) {
			return list.get(0);
		} else {
			return null;
		}
	}

}
